package integral

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralgoods"
	"private-domain-overseas-service/tools/ent/predicate"
)

type IntegralGoodsDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIntegralGoodsDao(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralGoodsDao {
	return &IntegralGoodsDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// IntegralGoodsCreate - 创建积分商城商品
func (l *IntegralGoodsDao) IntegralGoodsCreate(goods *ent.HzIntegralGoods, tx *ent.Tx) error {
	client := l.svcCtx.Orm.HzIntegralGoods
	if tx != nil {
		client = tx.HzIntegralGoods
	}
	err := client.Create().
		SetGoodsSmallImage(goods.GoodsSmallImage).
		SetGoodsImage(goods.GoodsImage).
		SetGoodsInfo(goods.GoodsInfo).
		SetGoodsPrice(goods.GoodsPrice).
		SetGoodsSort(goods.GoodsSort).
		SetGoodsStatus(goods.GoodsStatus).
		SetCreatedAt(goods.CreatedAt).
		SetUpdateAt(goods.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// IntegralGoodsUpdate - 编辑积分商城商品信息
func (l *IntegralGoodsDao) IntegralGoodsUpdate(goods *ent.HzIntegralGoods, tx *ent.Tx) error {
	client := l.svcCtx.Orm.HzIntegralGoods
	if tx != nil {
		client = tx.HzIntegralGoods
	}
	err := client.Update().SetGoodsSmallImage(goods.GoodsSmallImage).
		SetGoodsImage(goods.GoodsImage).
		SetGoodsInfo(goods.GoodsInfo).
		SetGoodsPrice(goods.GoodsPrice).
		SetGoodsSort(goods.GoodsSort).
		SetGoodsStatus(goods.GoodsStatus).
		SetUpdateAt(goods.UpdateAt).
		Where(hzintegralgoods.IDEQ(goods.ID)).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// IntegralGoodsConditionsFirst - 根据条件获取单个商品信息
func (l *IntegralGoodsDao) IntegralGoodsConditionsFirst(conditions ...predicate.HzIntegralGoods) (*ent.HzIntegralGoods, error) {
	goods, err := l.svcCtx.Orm.HzIntegralGoods.Query().Where(conditions...).First(l.ctx)
	if err != nil {
		return nil, err
	}
	return goods, nil
}

// IntegralGoodsConditionsPageAll -根据条件获取分页积分商城商品信息
func (l *IntegralGoodsDao) IntegralGoodsConditionsPageAll(page, pageSize int64, conditions ...predicate.HzIntegralGoods) ([]*ent.HzIntegralGoods, int64, error) {
	//计算分页偏移量
	offset := common.Offset(page, pageSize)

	//查询分页数据
	goodsInfos, err := l.svcCtx.Orm.HzIntegralGoods.Query().
		Where(conditions...).
		Offset(int(offset)).
		Limit(int(pageSize)).
		Order(ent.Desc(hzintegralgoods.FieldGoodsSort)).
		All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	//统计总数
	count, err := l.svcCtx.Orm.HzIntegralGoods.Query().
		Where(conditions...).Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}
	return goodsInfos, int64(count), nil
}
